package com.app.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.*;

import java.nio.charset.Charset;
import java.util.List;

/**
 * 配置Spring Mvc
 * @author ice
 */
@Configuration
@EnableWebMvc
@ComponentScan({"com.app.controller"})
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    PropertiesConfig propertiesConfig;


    /**
     * 设置响应编码
     * @return
     */
    @Bean
    public HttpMessageConverter<String> responseBodyConverter() {
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName(propertiesConfig.getEncoding()));
        return converter;
    }

    /**
     *全局消息转换器
     * @param converters
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(responseBodyConverter());
    }

    /**
     * 视图解析器
     * @param registry
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
        registry.jsp("/WEB-INF/jsp/",".jsp");
    }

    /**
     * 视图控制器
     * @param registry
     */
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("index");
        registry.addViewController("/index").setViewName("index");
        registry.addViewController("/teacher/login").setViewName("teacherLogin");
        registry.addViewController("/student/login").setViewName("studentLogin");
    }

    /**
     * 静态资源管理
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/statics/**").addResourceLocations("/statics/");
    }

    /**
     * Spring MVC 文件上传配置
     * @return
     */
    @Bean
    public CommonsMultipartResolver multipartResolver(){
        CommonsMultipartResolver commonsMultipartResolver= new CommonsMultipartResolver();
        commonsMultipartResolver.setMaxUploadSize(500000000);
        commonsMultipartResolver.setMaxInMemorySize(0);
        return  commonsMultipartResolver;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyIntercept()).addPathPatterns("/**").excludePathPatterns("/statics/**","/student/login","/teacher/login","/","/index","/teacher/teacherLogin","/student/studentLogin");
    }
}
